package com.ybkj.daijia.server.controller.vehicleInfo;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ybkj.daijia.api.common.responseBody.Response;
import com.ybkj.daijia.api.common.responseBody.ResponseCode;
import com.ybkj.daijia.api.common.responseBody.ResponseResult;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.except.NoPermissionException;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.DriverApply;
import com.ybkj.daijia.server.service.AreaService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.ZhuanxianService;
import com.ybkj.daijia.server.vehicleInfo.Vehicle;
import com.ybkj.daijia.server.service.vehicleInfo.VehicleService;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.naming.CompositeName;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

/***
 * @author: huguigang
 * @date: 2019-12-11
 * @description: 车辆操作controller
 */
@Controller
@RequestMapping(value = "vehicle")
@Slf4j
public class VehicleController {

    @Autowired
    private VehicleService vehicleService;

    @Autowired
    private CompanyService companyService;

    @RequestMapping("queryCompany")
    @ResponseBody
    public String queryCompany(){
        List<Company> companyList = companyService.findAll();
        ResponseResult rr = new ResponseResult(ResponseCode.SUCCESS);
        rr.setData(companyList);
        return rr.getResultJsonString();
    }

    /**
     * 下载批量导入车辆表格模板
     */
    @RequestMapping("downloadExcel")
    public void downloadVehicleExcel(HttpServletRequest request, HttpServletResponse response){
        String path = request.getSession().getServletContext().getRealPath("/");
        String sufPath = "upload/vehicleInfo";
        String fileName = "车辆上传模板.xlsx";
        File file = new File(path + "/" + sufPath + "/" + fileName);
        XSSFWorkbook workbook = null;
        FileInputStream fis = null;
        if (file.exists()) {
            try {
                fis = new FileInputStream(file);
                workbook = new XSSFWorkbook(fis);
                fis.close();
            } catch (FileNotFoundException e) {
                log.info("车辆上传模板文件未找到");
                e.printStackTrace();
            } catch (IOException e) {
                log.info("车辆上传模板文件读取失败");
                e.printStackTrace();
            }
        }
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        try {
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName,"utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            log.info("下载车辆上传模板文件失败");
            e.printStackTrace();
        }

    }

    @RequestMapping("vehiclePage")
    public ModelAndView vehicleView(){
        Subject subject = SecurityUtils.getSubject();
        ModelAndView mv = new ModelAndView();
        if(subject.isPermitted("zhuanxianCar")){
            mv.setViewName("vehicle/list");
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "jump", method = RequestMethod.GET)
    public ModelAndView jump() throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        ModelAndView mv = new ModelAndView();
        if (subject.isPermitted("zhuanxianCar")) {
            mv.setViewName("zhuanxian/cars");
            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "cars", method = RequestMethod.GET)
    public ModelAndView cars() throws ParseException {
        Subject subject = SecurityUtils.getSubject();
        ModelAndView mv = new ModelAndView();
        if (subject.isPermitted("zhuanxianCar")) {
            mv.setViewName("zhuanxian/cars");
            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    /**
     * 新增车辆
     * @param vehicleNumber 车牌号
     * @param vehicleName 车辆名称
     * @param companyId 公司id
     * @param appprovedPassengerCapacity 核定载客位
     * @param vehicleType 车辆类型
     * @param owner 车辆所有人
     * @param model 车辆品牌型号(厂牌+型号，例如：凯翼牌SQR7161J522/N)
     * @param engineNo 发动机号
     * @param registerDate 注册日期
     * @param issueDate 行驶证发证日期
     * @param vehicleVIN 车辆识别号
     * @return
     */
    @RequestMapping(value = "createVehicle", method = RequestMethod.POST)
    @ResponseBody
    public String createVehicle(@RequestParam("vehicleNumber") String vehicleNumber, @RequestParam("vehicleName") String vehicleName,
        @RequestParam("companyId") Long companyId, @RequestParam("vehicleType") String vehicleType,
        @RequestParam("appprovedPassengerCapacity") String appprovedPassengerCapacity, @RequestParam("owner") String owner,
        @RequestParam("model") String model, @RequestParam("engineNo") String engineNo,
        @RequestParam("registerDate") String registerDate, @RequestParam("issueDate") String issueDate,
        @RequestParam("vehicleVIN") String vehicleVIN){
        //查询车牌号是否存在
        List<Vehicle> vehicles = vehicleService.getCarByCarNumber(vehicleNumber);
        if(vehicles.size() > 0){
            return new ResponseResult(ResponseCode.CAR_EXISTEND).getResultJsonString();
        }
        Vehicle newVehicle = new Vehicle();
        newVehicle.setId(IdWorker.getIdStr());
        newVehicle.setCarNumber(vehicleNumber);
        newVehicle.setCarName(vehicleName);
        newVehicle.setCompanyId(companyId);
        newVehicle.setVehicleType(vehicleType);
        newVehicle.setAppprovedPassengerCapacity(appprovedPassengerCapacity);
        newVehicle.setUpdated(LocalDateTime.now());
        newVehicle.setOwner(owner);
        newVehicle.setEngineNum(engineNo);
        newVehicle.setRegisterDate(registerDate);
        newVehicle.setIssueDate(issueDate);
        newVehicle.setVin(vehicleVIN);
        newVehicle.setModel(model);
        Company company = companyService.findOne(Long.valueOf(companyId));
        newVehicle.setCompanyName(company.getCompanyName());
        vehicleService.createVehicle(newVehicle);
        return new ResponseResult(ResponseCode.SUCCESS).getResultJsonString();
    }

    /**
     * 删除车辆
     * @param id 车辆id
     * @return
     */
    @RequestMapping("deleteVehicle")
    @ResponseBody
    public String deleteVehicle(@RequestParam(value = "id", required = false) String id,
                                @RequestParam(value = "vehicleNumber", required = false) String vehicleNumber){
        //查询车辆是否存在
        List<Vehicle> vehicles = vehicleService.getCarByCarNumber(vehicleNumber);
        if(null == vehicles || vehicles.size() < 1){
            return new ResponseResult(ResponseCode.CAR_NONEXITENT).getResultJsonString();
        }
        vehicleService.deleteCar(id);
        return new ResponseResult(ResponseCode.SUCCESS).getResultJsonString();
    }

    /**
     * 修改车辆信息
     * @param id 车辆id
     * @param carNumber 车辆号牌
     * @return
     */
    @RequestMapping("editVehicle")
    @ResponseBody
    public String editVehicle(@RequestParam("id") String id, @RequestParam(value = "companyId", required = false) Long companyId,
                        @RequestParam(value = "companyName", required = false) String companyName, @RequestParam(value = "carName",required = false) String carName,
                        @RequestParam(value = "carNumber",required = false) String carNumber, @RequestParam(value = "carColor", required = false) String carColor,
                        @RequestParam(value = "drivingDistance", required = false) Double drivingDistance, @RequestParam(value = "plateColor", required = false) String plateColor,
                        @RequestParam(value = "vehicleType",required = false) String vehicleType, @RequestParam(value = "owner",required = false) String owner,
                        @RequestParam(value = "useCharacter",required = false) String useCharacter, @RequestParam(value = "address",required = false) String address,
                        @RequestParam(value = "model",required = false) String model, @RequestParam(value = "vin",required = false) String vin,
                        @RequestParam(value = "engineNum",required = false) String engineNum, @RequestParam(value = "registerDate",required = false) String registerDate,
                        @RequestParam(value = "issueDate",required = false) String issueDate, @RequestParam(value = "stopDate",required = false) String stopDate,
                        @RequestParam(value = "fileNum",required = false) String fileNum, @RequestParam(value = "appprovedPassengerCapacity",required = false) String appprovedPassengerCapacity,
                        @RequestParam(value = "grossMass",required = false) String grossMass, @RequestParam(value = "unladenMass",required = false) String unladenMass,
                        @RequestParam(value = "approvedLoad",required = false) String approvedLoad, @RequestParam(value = "tractionMass",required = false) String tractionMass,
                        @RequestParam(value = "inspectionRecord",required = false) String inspectionRecord, @RequestParam(value = "overallDimension",required = false) String overallDimension,
                        @RequestParam(value = "fuelType",required = false) String fuelType, @RequestParam(value = "engineDisplace",required = false) String engineDisplace,
                        @RequestParam(value = "transAgencyt",required = false) String transAgencyt, @RequestParam(value = "transArea",required = false) String transArea,
                        @RequestParam(value = "certifyDate",required = false) String certifyDate, @RequestParam(value = "fixState",required = false) String fixState,
                        @RequestParam(value = "checkState",required = false) String checkState, @RequestParam(value = "feePrintId",required = false) String feePrintId,
                        @RequestParam(value = "GPSBrand",required = false) String GPSBrand, @RequestParam(value = "GPSModel",required = false) String GPSModel,
                        @RequestParam(value = "GPSInstallDate",required = false) String GPSInstallDate, @RequestParam(value = "reportedDate",required = false) String reportedDate,
                        @RequestParam(value = "commercialType",required = false) Integer commercialType, @RequestParam(value = "fareType",required = false) String fareType){
        //查询车辆是否存在
        Vehicle vehicle = vehicleService.getVehicleById(id);
        if(null == vehicle){
            return new ResponseResult(ResponseCode.CAR_NONEXITENT).getResultJsonString();
        }
        DriverApply da = new DriverApply();
        
        vehicle.setCompanyId(companyId);
        vehicle.setCompanyName(companyName);
        vehicle.setCarName(carName);
        vehicle.setCarNumber(carNumber);
        vehicle.setCarColor(carColor);
        vehicle.setDrivingDistance(drivingDistance);
        vehicle.setPlateColor(plateColor);
        vehicle.setVehicleType(vehicleType);
        vehicle.setOwner(owner);
        vehicle.setUseCharacter(useCharacter);
        vehicle.setAddress(address);
        vehicle.setModel(model);
        vehicle.setRegisterDate(registerDate);
        vehicle.setEngineNum(engineNum);
        vehicle.setIssueDate(issueDate);
        vehicle.setStopDate(stopDate);
        vehicle.setFileNum(fileNum);
        vehicle.setAppprovedPassengerCapacity(appprovedPassengerCapacity);
        vehicle.setGrossMass(grossMass);
        vehicle.setUnladenMass(unladenMass);
        vehicle.setApprovedLoad(approvedLoad);
        vehicle.setTractionMass(tractionMass);
        vehicle.setInspectionRecord(inspectionRecord);
        vehicle.setOverallDimension(overallDimension);
        vehicle.setFuelType(fuelType);
        vehicle.setEngineDisplace(engineDisplace);
        vehicle.setTransAgencyt(transAgencyt);
        vehicle.setTransArea(transArea);
        vehicle.setCertifyDate(certifyDate);
        vehicle.setFixState(fixState);
        vehicle.setCheckState(checkState);
        vehicle.setFeePrintId(feePrintId);
        vehicle.setGPSBrand(GPSBrand);
        vehicle.setGPSModel(GPSModel);
        vehicle.setGPSInstallDate(GPSInstallDate);
        vehicle.setReportedDate(reportedDate);
        vehicle.setCommercialType(commercialType);
        vehicle.setFareType(fareType);
        vehicle.setUpdated(LocalDateTime.now());
        vehicleService.editVehicle(vehicle);
        return new ResponseResult(ResponseCode.SUCCESS).getResultJsonString();
    }

    /**
     * 多条件查询车辆信息
     * @param vehicleNumber 车牌号
     * @param companyId 公司Id
     * @param driverName 驾驶员名
     * @param driverPhone 驾驶员手机
     * @param userName 驾驶员工号
     * @return
     */
    @RequestMapping("getVehiclesByParams")
    @ResponseBody
    public String getVehiclesByParams(@RequestParam(value = "vehicleNumber", required = false) String vehicleNumber, @RequestParam(value = "companyId", required = false) String companyId,
                            @RequestParam(value = "driverName", required = false) String driverName,
                            @RequestParam(value = "driverPhone", required = false) String driverPhone, @RequestParam(value = "userName", required = false) String userName){
        ResponseResult rr = new ResponseResult(ResponseCode.SUCCESS);
        List<Vehicle> vehicleList = vehicleService.getVehiclesByParams(vehicleNumber,companyId,driverName,driverPhone,userName);
        rr.setData(vehicleList);
        return rr.getResultJsonString();
    }

    /**
     * 行驶证上传接口
     * @param type 行驶证正/反面（front：正面，back：反面）
     * @return
     */
    @RequestMapping(value = "uploadDrivingLicense", method = RequestMethod.POST)
    @ResponseBody
    public String uploadDrivingLicense(@RequestParam("file") MultipartFile multipartFile, @RequestParam("type") String type,
                                        HttpServletRequest request, HttpServletResponse response) {
        String mtFileName = multipartFile.getOriginalFilename();
        String basePath= "";
        try {
            basePath = WebUtils.getRealPath(request.getSession().getServletContext(), "/");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        File dir = new File(basePath,"/upload/drivingLicense");
        // 判断文件夹是否存在,不存在则创建
        if(!dir.exists()){
            dir.mkdir();
        }
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        String fileName = String.format("%s.jpg",uuid);
        File file = new File(dir,fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            byte[] size = multipartFile.getBytes();
            IOUtils.write(size, fos);
            fos.close();
        } catch (IOException e){
            e.printStackTrace();
        }

        ResponseResult rr = new ResponseResult(ResponseCode.SUCCESS);
        if("front".equals(type)){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code",200);
            jsonObject.put("msg","OK");
            jsonObject.put("requestId","81121B0B-2BFE-44BA-9825-C15CA5E99551");
            JSONObject data = new JSONObject();
            data.put("code",200);
            data.put("msg","OK");
            data.put("dataId","test3faX7kc7bIy6TU$enTW0nt-1pPFFA");
            data.put("taskId","img1CVBf$Vgrno7wF75H5LaRm-1pPFFA");
            data.put("url","http://192.168.110.145:8080/upload/drivingLicense/"+fileName);
            data.put("fileName",fileName);
            data.put("extras",new JSONObject());
            JSONObject result = new JSONObject();
            result.put("label","ocr");
            result.put("scene","ocr");
            result.put("rate",99.91);
            result.put("suggestion","review");
            List results = new ArrayList<>();
            results.add(result);
            JSONObject photoInfo = new JSONObject();
            photoInfo.put("address","宜宾临港经济开发区龙头山路199号2号楼西南互联网产业基地526室");
            photoInfo.put("engineNum", "BEKD00171");
            photoInfo.put("registerDate", "2019-07-11");
            photoInfo.put("useCharacter", "重型厢式货车");
            photoInfo.put("vehicleType", "小型轿车");
            photoInfo.put("issueDate", "2019-07-11");
            photoInfo.put("model", "凯翼牌SQR7161J522/N");
            photoInfo.put("owner", "四川云步科技有限公司");
            photoInfo.put("plateNum", "川Q722G3");
            photoInfo.put("vin", "LVVDC11B9KD085470");
            result.put("vehicleLicenseFrontInfo",photoInfo);
            data.put("results",results);
            jsonObject.put("data",data);
            rr.setData(jsonObject);
        }
        if("back".equals(type)){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code",200);
            jsonObject.put("msg","OK");
            jsonObject.put("requestId","05647e07-a0d8-4963-a9c3-b3266b24a45a");
            JSONObject data = new JSONObject();
            data.put("dataId","4a5fa760-e2de-4945-91ee-799d27293654");
            data.put("taskId","img1CVBf$Vgrno7wF75H5LaRm-1pPFFA");
            data.put("code",200);
            data.put("msg","OK");
            data.put("url","http://192.168.110.145:8080/upload/drivingLicense/"+fileName);
            data.put("fileName",fileName);
            data.put("extras",new JSONObject());
            JSONObject result = new JSONObject();
            result.put("label","ocr");
            result.put("rate",99.91);
            result.put("scene","ocr");
            result.put("suggestion","review");
            List results = new ArrayList<>();
            results.add(result);
            JSONObject photoInfo = new JSONObject();
            photoInfo.put("appprovedPassengerCapacity",5);
            photoInfo.put("approvedLoad", "");
            photoInfo.put("fileNum", "511502046931");
            photoInfo.put("grossMass", "1651kg");
            photoInfo.put("inspectionRecord", "检验有效期至2020年07月川Q(01)");
            photoInfo.put("plateNum", "川Q722G3");
            photoInfo.put("tractionMass", "");
            photoInfo.put("unladenMass", "1276kg");
            JSONObject overall = new JSONObject();
            overall.put("height",1493);
            overall.put("length",4450);
            overall.put("width",1748);
            photoInfo.put("overallDimension",overall);
            result.put("vehicleLicenseBackInfo",photoInfo);
            data.put("results",results);
            jsonObject.put("data",data);
            rr.setData(jsonObject);
        }

        return rr.getResultJsonString();
    }

}
